package com.zrx.app.android.service;


import android.app.Application;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zrx.app.android.Constants;
import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.NetworkStatus;
import com.zrx.app.android.UTIL.RemoteConn;
import com.zrx.app.android.UTIL.ZRXUTIL;
import com.zrx.app.android.activity.BaseActivity;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by liuji on 2017/4/15.
 */

public class UploadService extends Service {
    private static final String TAG = "UploadService";
    private static final int MAX_RETRY_TIMES = 10;    //最大重试次数
    ZRXAsyncTask backgroundThread = null;
    ConcurrentLinkedQueue<JSONObject> clq = new ConcurrentLinkedQueue<>();
    NotificationManager mNotificationManager = null;
    NotificationCompat.Builder mNotifyBuilder = null;
    int notifyID = 1;
    private int count = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        backgroundThread = new ZRXAsyncTask();
        backgroundThread.execute();

        JSONObject scanTask = new JSONObject();
        scanTask.put("taskName", "scan");
        clq.add(scanTask);

        JSONObject countTask = new JSONObject();
        countTask.put("taskName", "countTask");
        clq.add(countTask);

//        BroadcastReceiver receiver=new BroadcastReceiver();
//        IntentFilter filter=new IntentFilter();
//        filter.addAction(Intent.ACTION_TIME_TICK);
//        registerReceiver(receiver,filter);

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");


    String jobState = "";

    public void countTask() {
        mNotifyBuilder = new NotificationCompat.Builder(this)

                .setContentTitle("zrx")
                .setContentText(sdf.format(new Date()) + ":" + jobState)
                .setSmallIcon(R.mipmap.logo)
                .setNumber(count);
        ;
        mNotificationManager.notify(
                notifyID,
                mNotifyBuilder.build());
        try {



            Thread.sleep(10000);
            JSONObject countTask = new JSONObject();
            countTask.put("taskName", "countTask");
            clq.add(countTask);

            JSONObject scanTask = new JSONObject();
            scanTask.put("taskName", "scan");
            clq.add(scanTask);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {

            String taskJson = intent.getStringExtra("taskJson");
            if (taskJson == null) return START_STICKY;
            JSONObject json = JSON.parseObject(taskJson);
            clq.add(json);
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }

//        handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
        Log.d(TAG, "ZRX onStartCommand");
        return START_STICKY;
    }

    public class ZRXAsyncTask extends AsyncTask {
        @Override
        protected Object doInBackground(Object[] params) {
            while (!isCancelled()) {
                try {
                    if (!NetworkStatus.isNetworkAvailable(getApplicationContext())) {
                        Thread.sleep(1000);
                        continue;
                    }
                    JSONObject taskJson = clq.poll();
                    String taskName = taskJson.getString("taskName");
                    if ("审核提交".equals(taskName))
                        doAuditSubmit(taskJson);
                    else if ("放款提交".equals(taskName))
                        doLoanSubmit(taskJson);
                    else if ("车商收据提交".equals(taskName))
                        doLoanReceiptSubmit(taskJson);
                    else if ("放车提交".equals(taskName))
                        doCarDeliverSubmit(taskJson);
                    else if ("scan".equals(taskName))
                        doScan();
                    else if ("countTask".equals(taskName))
                        countTask();
                } catch (Exception e) {
                    Log.d(TAG, e.getMessage());
                }
            }
            return null;
        }



        private void doScan() {
            try {
                Log.d(TAG, "start doScan");
                File dir = new File(ZRXUTIL.getPath());
                if (dir.exists() && dir.isDirectory()) {
                    for (String id : dir.list()) {
                        try {
                            JSONObject record = ZRXUTIL.getRecordJson(id);
                            String state = record.getString("state");
                            if ("审核提交".equals(state)) {
                                if(!record.containsKey("auditState")||!record.getString("auditState").equals("完成")) {
                                    JSONObject json = new JSONObject();
                                    json.put("id", id);
                                    json.put("taskName", "审核提交");
                                    clq.add(json);
                                }
                            }else if ("放款提交".equals(state)) {
                                if(!record.containsKey("loanState")||!record.getString("loanState").equals("完成")) {
                                    JSONObject json = new JSONObject();
                                    json.put("id", id);
                                    json.put("taskName", "放款提交");
                                    clq.add(json);
                                }
                            }else if ("车商收据提交".equals(state)) {
                                if(!record.containsKey("loanReceiptState")||!record.getString("loanReceiptState").equals("完成")) {
                                    JSONObject json = new JSONObject();
                                    json.put("id", id);
                                    json.put("taskName", "车商收据提交");
                                    clq.add(json);
                                }
                            }else if ("放车提交".equals(state)) {
                                if(!record.containsKey("carDeliverState")||!record.getString("carDeliverState").equals("完成")) {
                                    JSONObject json = new JSONObject();
                                    json.put("id", id);
                                    json.put("taskName", "放车提交");
                                    clq.add(json);
                                }
                            }

                        } catch (Exception e) {

                        }

                    }
                }
                Log.d(TAG, "end doScan");
            } catch (Exception e) {

            }
        }

        void appendInfo(String info) {
            try {
                FileWriter fw = new FileWriter(new File(ZRXUTIL.getPath() + "/bgInfo.txt"), true);
                fw.write(info + "\n");
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void doLoanReceiptSubmit(JSONObject taskJson) {     //上传部分
            final String srcStateName="loanReceiptState";
            String id = taskJson.getString("id");
            JSONObject record = ZRXUTIL.getRecordJson(id);
            try {
                String state = record.getString("state");
                if ("车商收据提交".equals(state)) {
                    JSONArray log=record.getJSONArray("log");
                    if(log==null){
                        log=new JSONArray();
                        record.put("log",log);
                    }
                    JSONArray retryLog=record.getJSONArray("retryLog");
                    if(retryLog==null){
                        retryLog=new JSONArray();
                        record.put("retryLog",retryLog);
                    }
                    if(retryLog.size()>MAX_RETRY_TIMES/2){
                       Handler handler=new Handler(Looper.getMainLooper());
                        handler.post(new Runnable(){
                            public void run(){
                                Toast.makeText(getApplicationContext(), "当前网络不佳，请移至网络优良环境进行。", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    if(retryLog.size()>MAX_RETRY_TIMES){
                        log.add(sdf.format(new Date())+"重试次数大于"+MAX_RETRY_TIMES+"次,请联系技术人员");
                        appendInfo(sdf.format(new Date())+"车商收据提交（"+id+"）重试次数大于"+MAX_RETRY_TIMES+"次,请联系技术人员");
                        record.remove("state");
                        record.remove("editable");
                        record.remove(srcStateName);
                        record.remove("retryLog");

                        //clq.removeIf(e->e!=null&&e.getJSONObject("id").equals(id));
                        return;
                    }
                    if(!record.containsKey(srcStateName)) {
                        record.put(srcStateName, "第一阶段");
                        log.add(sdf.format(new Date())+":车商收据提交第一阶段开始");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("第一阶段")){
                        log.add(sdf.format(new Date())+":车商收据提交第一阶段继续");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("第二阶段")){
                        log.add(sdf.format(new Date())+":车商收据提交第二阶段继续");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("完成")){
                        return;
                    }else {
                        log.add(sdf.format(new Date()) + ":未知状态:" + state);
                        retryLog.add(sdf.format(new Date()));
                        appendInfo(sdf.format(new Date()) + ":未知状态:" + state);
                        return;
                    }

                    appendInfo(sdf.format(new Date()) + ":车商收据提交开始.id=:" + id);
                    JSONObject rawRecord = record.getJSONObject("rawRecord");

                    String email = record.getString("email");
                    String password = record.getString("password");
                    RemoteConn ins = RemoteConn.createPrivateInstance(email, password);
                    boolean flag_ok = true;
                    if ("第一阶段".equals(record.getString(srcStateName))) {
                        File moduleDir = new File(ZRXUTIL.getPath() + "/" + id + "/车商收据");
                        if (moduleDir.exists() && moduleDir.isDirectory()) {
                            File[] files = moduleDir.listFiles();
                            if (files != null) {
                                for (File file : files) {
                                    if (file.exists() && file.isFile() && !(file.getName().lastIndexOf(".raw") > -1)) {
                                        String key = file.getName().substring(0, file.getName().lastIndexOf("."));
                                        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
                                        JSONObject re = ins.uploadFilesByUrl("/tango/loan/uploadLoanReceiptPics/"+id,key,file.getAbsolutePath(),suffix);
                                        if (re != null
                                                && re.containsKey("code")
                                                && re.getInteger("code").equals(0)
                                                && re.containsKey("details")) {
                                            JSONObject details = re.getJSONObject("details");
                                            Set<String> resultDetailsKeySet = details.keySet();
                                            jobState = record.getString("id");
                                            for (String detailKey : resultDetailsKeySet) {
                                                if ("上传失败".equals(details.getString(detailKey))) {
                                                    flag_ok = false;
                                                    jobState += detailKey + " failed;";
                                                    appendInfo("车商收据提交文件上传失败:" + detailKey + ".id=:" + id);
                                                } else {
                                                    appendInfo("车商收据提交文件上传成功:" + detailKey + ".id=:" + id);
                                                    file.delete();
                                                }
                                            }
                                            record.put("rawRecord", re.getJSONObject("data"));
                                            ZRXUTIL.saveState(record, true);
                                        } else
                                            flag_ok = false;
                                    }
                                }
                            }
                        }
                        if(flag_ok){
                            log.add(sdf.format(new Date()) + ":车商收据提交第一阶段完成");
                            appendInfo(sdf.format(new Date()) + ":车商收据提交第一阶段完成.id=" + id);

                            record.put(srcStateName, "第二阶段");
                        }else{
                            log.add(sdf.format(new Date()) + ":车商收据提交第一阶段失败");
                        }
                    }

                    if ("第二阶段".equals(record.getString(srcStateName))) {
                        JSONObject re = ins.submitByUrl("/tango/loan/toLoanReceiptConfirming/"+id);
                        if (re != null && re.containsKey("code") && re.getInteger("code").equals(0)) {
                            record.put("rawRecord", re.getJSONObject("data"));
                            record.remove("editable");
                            record.remove("state");
                            record.remove(srcStateName);
                            record.remove("retryLog");

                            appendInfo(sdf.format(new Date()) + ":车商收据提交第二阶段完成.id=" + id);
                            appendInfo(sdf.format(new Date()) + ":车商收据提交成功.id=" + id);
                            log.add(sdf.format(new Date()) + ":车商收据提交完成");

                        } else {
                            appendInfo(sdf.format(new Date()) + ":车商收据提交失败.id=" + id + "." + (re == null ? "" : re.getString("msg")));
                        }
                    }

                }
            } catch (Exception e) {
                appendInfo(sdf.format(new Date())+" 车商收据提交异常 id=" + id + "." + e.getMessage());
            } finally {
                ZRXUTIL.saveState(record,true);
            }
        }

        private void doCarDeliverSubmit(JSONObject taskJson) {
            final String srcStateName="carDeliverState";
            String id = taskJson.getString("id");
            JSONObject record = ZRXUTIL.getRecordJson(id);
            try {
                String state = record.getString("state");
                if ("放车提交".equals(state)) {
                    JSONArray log=record.getJSONArray("log");
                    if(log==null){
                        log=new JSONArray();
                        record.put("log",log);
                    }
                    JSONArray retryLog=record.getJSONArray("retryLog");
                    if(retryLog==null){
                        retryLog=new JSONArray();
                        record.put("retryLog",retryLog);
                    }
                    if(retryLog.size()>MAX_RETRY_TIMES/2){
                        Handler handler=new Handler(Looper.getMainLooper());
                        handler.post(new Runnable(){
                            public void run(){
                                Toast.makeText(getApplicationContext(), "当前网络不佳，请移至网络优良环境进行。", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    if(retryLog.size()>MAX_RETRY_TIMES){
                        log.add(sdf.format(new Date())+"重试次数大于"+MAX_RETRY_TIMES+"次,请联系技术人员");
                        appendInfo(sdf.format(new Date())+"放车提交（"+id+"）重试次数大于"+MAX_RETRY_TIMES+"次,请联系技术人员");
                        record.remove("state");
                        record.remove("editable");
                        record.remove(srcStateName);
                        record.remove("retryLog");

                        //clq.removeIf(e->e!=null&&e.getJSONObject("id").equals(id));
                        return;
                    }
                    if(!record.containsKey(srcStateName)) {
                        record.put(srcStateName, "第一阶段");
                        log.add(sdf.format(new Date())+":放车提交第一阶段开始");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("第一阶段")){
                        log.add(sdf.format(new Date())+":放车提交第一阶段继续");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("第二阶段")){
                        log.add(sdf.format(new Date())+":放车提交第二阶段继续");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("完成")){
                        return;
                    }else {
                        log.add(sdf.format(new Date()) + ":未知状态:" + state);
                        retryLog.add(sdf.format(new Date()));
                        appendInfo(sdf.format(new Date()) + ":未知状态:" + state);
                        return;
                    }

                    appendInfo(sdf.format(new Date()) +":放车提交开始.id=" + id);
                    JSONObject rawRecord = record.getJSONObject("rawRecord");

                    String email = record.getString("email");
                    String password = record.getString("password");
                    RemoteConn ins = RemoteConn.createPrivateInstance(email, password);
                    boolean flag_ok = true;
                    if ("第一阶段".equals(record.getString(srcStateName))) {
                        File moduleDir = new File(ZRXUTIL.getPath() + "/" + id + "/放车");
                        if (moduleDir.exists() && moduleDir.isDirectory()) {
                            File[] files = moduleDir.listFiles();
                            if (files != null) {
                                for (File file : files) {
                                    if (file.exists() && file.isFile() && !(file.getName().lastIndexOf(".raw") > -1)) {
                                        String key = file.getName().substring(0, file.getName().lastIndexOf("."));
                                        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
                                        JSONObject re = ins.uploadFilesByUrl("/tango/car/uploadCarDeliverPics/"+id,key,file.getAbsolutePath(),suffix);
                                        if (re != null
                                                && re.containsKey("code")
                                                && re.getInteger("code").equals(0)
                                                && re.containsKey("details")) {
                                            JSONObject details = re.getJSONObject("details");
                                            Set<String> resultDetailsKeySet = details.keySet();
                                            jobState = record.getString("id");
                                            for (String detailKey : resultDetailsKeySet) {
                                                if ("上传失败".equals(details.getString(detailKey))) {
                                                    flag_ok = false;
                                                    jobState += detailKey + " failed;";
                                                    appendInfo("放车提交文件上传失败:" + detailKey + ".id=:" + id);
                                                } else {
                                                    appendInfo("放车提交文件上传成功:" + detailKey + ".id=:" + id);
                                                    file.delete();
                                                }
                                            }
                                            record.put("rawRecord", re.getJSONObject("data"));
                                            ZRXUTIL.saveState(record, true);
                                        } else
                                            flag_ok = false;
                                    }
                                }
                            }
                        }
                        if(flag_ok){
                            log.add(sdf.format(new Date()) + ":放车提交第一阶段完成");
                            appendInfo(sdf.format(new Date()) + ":放车提交第一阶段完成.id=" + id);

                            record.put(srcStateName, "第二阶段");
                        }else{
                            log.add(sdf.format(new Date()) + ":放车提交第一阶段失败");
                        }
                    }

                    if ("第二阶段".equals(record.getString(srcStateName))) {
                        JSONObject re = ins.submitByUrl("/tango/car/toStateCAR_EXAMING/"+id);
                        if (re != null && re.containsKey("code") && re.getInteger("code").equals(0)) {
                            record.put("rawRecord", re.getJSONObject("data"));
                            record.remove("editable");
                            record.remove("state");
                            record.remove(srcStateName);
                            record.remove("retryLog");

                            appendInfo(sdf.format(new Date()) + ":放车提交第二阶段完成.id=" + id);
                            appendInfo(sdf.format(new Date()) + ":放车提交成功.id=" + id);
                            log.add(sdf.format(new Date()) + ":放车提交完成");

                        } else {
                            appendInfo(sdf.format(new Date()) + ":放车提交失败.id=" + id + "." + (re == null ? "" : re.getString("msg")));
                        }
                    }

                }
            } catch (Exception e) {
                appendInfo(sdf.format(new Date())+" 放车提交异常 id=" + id + "." + e.getMessage());
            } finally {
                ZRXUTIL.saveState(record,true);
            }
        }

        private void doLoanSubmit(JSONObject taskJson) {
            final String srcStateName="loanState";
            String id = taskJson.getString("id");
            JSONObject record = ZRXUTIL.getRecordJson(id);
            try {
                String state = record.getString("state");
                if ("放款提交".equals(state)) {
                    JSONArray log=record.getJSONArray("log");
                    if(log==null){
                        log=new JSONArray();
                        record.put("log",log);
                    }
                    JSONArray retryLog=record.getJSONArray("retryLog");
                    if(retryLog==null){
                        retryLog=new JSONArray();
                        record.put("retryLog",retryLog);
                    }
                    if(retryLog.size()>MAX_RETRY_TIMES/2){
                        Handler handler=new Handler(Looper.getMainLooper());
                        handler.post(new Runnable(){
                            public void run(){
                                Toast.makeText(getApplicationContext(), "当前网络不佳，请移至网络优良环境进行。", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    if(retryLog.size()>MAX_RETRY_TIMES){
                        log.add(sdf.format(new Date())+"重试次数大于"+MAX_RETRY_TIMES+"次,请联系技术人员");
                        appendInfo(sdf.format(new Date())+"放款提交（"+id+"）重试次数大于"+MAX_RETRY_TIMES+"次,请联系技术人员");
                        record.remove("state");
                        record.remove("editable");
                        record.remove(srcStateName);
                        record.remove("retryLog");

                        //clq.removeIf(e->e!=null&&e.getJSONObject("id").equals(id));
                        return;
                    }
                    if(!record.containsKey(srcStateName)) {
                        record.put(srcStateName, "第一阶段");
                        log.add(sdf.format(new Date())+":放款提交第一阶段开始");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("第一阶段")){
                        log.add(sdf.format(new Date())+":放款提交第一阶段继续");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("第二阶段")){
                        log.add(sdf.format(new Date())+":放款提交第二阶段继续");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("完成")){
                        return;
                    }else {
                        log.add(sdf.format(new Date()) + ":未知状态:" + state);
                        retryLog.add(sdf.format(new Date()));
                        appendInfo(sdf.format(new Date()) + ":未知状态:" + state);
                        return;
                    }

                    appendInfo(sdf.format(new Date()) + "放款提交开始 id=" + id);
                    JSONObject rawRecord = record.getJSONObject("rawRecord");

                    String email = record.getString("email");
                    String password = record.getString("password");
                    RemoteConn ins = RemoteConn.createPrivateInstance(email, password);
                    boolean flag_ok = true;
                    if ("第一阶段".equals(record.getString(srcStateName))) {
                        File moduleDir = new File(ZRXUTIL.getPath() + "/" + id + "/放款");
                        if (moduleDir.exists() && moduleDir.isDirectory()) {
                            File[] files = moduleDir.listFiles();
                            if (files != null) {
                                for (File file : files) {
                                    if (file.exists() && file.isFile() && !(file.getName().lastIndexOf(".raw") > -1)) {
                                        String key = file.getName().substring(0, file.getName().lastIndexOf("."));
                                        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
                                        JSONObject re = ins.uploadFilesByUrl("/tango/loan/uploadLoanPics/"+id,key,file.getAbsolutePath(),suffix);
                                        if (re != null
                                                && re.containsKey("code")
                                                && re.getInteger("code").equals(0)
                                                && re.containsKey("details")) {
                                            JSONObject details = re.getJSONObject("details");
                                            Set<String> resultDetailsKeySet = details.keySet();
                                            jobState = record.getString("id");
                                            for (String detailKey : resultDetailsKeySet) {
                                                if ("上传失败".equals(details.getString(detailKey))) {
                                                    flag_ok = false;
                                                    jobState += detailKey + " failed;";
                                                    appendInfo("放款提交文件上传失败:" + detailKey + ".id=:" + id);
                                                } else {
                                                    appendInfo("放款提交文件上传成功:" + detailKey + ".id=:" + id);
                                                    file.delete();
                                                }
                                            }
                                            record.put("rawRecord", re.getJSONObject("data"));
                                            ZRXUTIL.saveState(record, true);
                                        } else
                                            flag_ok = false;
                                    }
                                }
                            }
                        }
                        if(flag_ok){
                            log.add(sdf.format(new Date()) + ":放款提交第一阶段完成");
                            appendInfo(sdf.format(new Date()) + ":放款提交第一阶段完成.id=" + id);

                            record.put(srcStateName, "第二阶段");
                        }else{
                            log.add(sdf.format(new Date()) + ":放款提交第一阶段失败");
                        }
                    }

                    if ("第二阶段".equals(record.getString(srcStateName))) {
                        JSONObject re = ins.submitByUrl("/tango/loan/toLoanExaming/"+id);
                        if (re != null && re.containsKey("code") && re.getInteger("code").equals(0)) {
                            record.put("rawRecord", re.getJSONObject("data"));
                            record.remove("editable");
                            record.remove("state");
                            record.remove(srcStateName);
                            record.remove("retryLog");

                            appendInfo(sdf.format(new Date()) + ":放款提交第二阶段完成.id=" + id);
                            appendInfo(sdf.format(new Date()) + ":放款提交成功.id=" + id);
                            log.add(sdf.format(new Date()) + ":放款提交完成");

                        } else {
                            appendInfo(sdf.format(new Date()) + ":放款提交失败.id=" + id + "." + (re == null ? "" : re.getString("msg")));
                        }
                    }

                }
            } catch (Exception e) {
                appendInfo(sdf.format(new Date())+" 放款提交异常 id=" + id + "." + e.getMessage());
            } finally {
                ZRXUTIL.saveState(record,true);
            }
        }

        private void doAuditSubmit(JSONObject taskJson) {
            String id = taskJson.getString("id");
            JSONObject record = ZRXUTIL.getRecordJson(id);
            final String srcStateName="auditState";
            try {
                String state = record.getString("state");
                if ("审核提交".equals(state)) {
                    JSONArray log=record.getJSONArray("log");
                    if(log==null){
                        log=new JSONArray();
                        record.put("log",log);
                    }
                    JSONArray retryLog=record.getJSONArray("retryLog");
                    if(retryLog==null){
                        retryLog=new JSONArray();
                        record.put("retryLog",retryLog);
                    }
                    if(retryLog.size()>MAX_RETRY_TIMES/2){
                        Handler handler=new Handler(Looper.getMainLooper());
                        handler.post(new Runnable(){
                            public void run(){
                                Toast.makeText(getApplicationContext(), "当前网络不佳，请移至网络优良环境进行。", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    if(retryLog.size()>MAX_RETRY_TIMES){
                        log.add(sdf.format(new Date())+"重试次数大于"+MAX_RETRY_TIMES+"次,请联系技术人员");
                        appendInfo(sdf.format(new Date())+"审核提交（"+id+"）重试次数大于"+MAX_RETRY_TIMES+"次,请联系技术人员");
                        record.remove("state");
                        record.remove("editable");
                        record.remove(srcStateName);
                        record.remove("retryLog");
                        //clq.removeIf(e->e!=null&&e.getJSONObject("id").equals(id));
                        return;
                    }

                    if(!record.containsKey(srcStateName)) {
                        record.put(srcStateName, "第一阶段");
                        log.add(sdf.format(new Date())+":审核提交第一阶段开始");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("第一阶段")){
                        log.add(sdf.format(new Date())+":审核提交第一阶段继续");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("第二阶段")){
                        log.add(sdf.format(new Date())+":审核提交第二阶段继续");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("第三阶段")){
                        log.add(sdf.format(new Date())+":审核提交第三阶段继续");
                        retryLog.add(sdf.format(new Date()));
                    }else if(record.getString(srcStateName).equals("完成")){
                        return;
                    }else {
                        log.add(sdf.format(new Date()) + ":未知状态:" + state);
                        retryLog.add(sdf.format(new Date()));
                        appendInfo(sdf.format(new Date()) + ":未知状态:" + state);
                        return;
                    }

                    appendInfo(sdf.format(new Date()) + "审核提交开始 id=" + id);
                    JSONObject rawRecord = record.getJSONObject("rawRecord");
                    JSONObject src = new JSONObject();
                    if(rawRecord.containsKey("basicData")&&rawRecord.get("basicData")instanceof JSONObject)
                        src.putAll(rawRecord.getJSONObject("basicData"));
                    if(rawRecord.containsKey("paymentInfo")&&rawRecord.get("paymentInfo")instanceof JSONObject)
                        src.putAll(rawRecord.getJSONObject("paymentInfo"));
                    if(rawRecord.containsKey("addtionalData")&&rawRecord.get("addtionalData")instanceof JSONObject)
                        src.putAll(rawRecord.getJSONObject("addtionalData"));

                    JSONObject uploadText = new JSONObject();

                    JSONObject auditRecord = record.getJSONObject("auditRecord");
                    Iterator<Map.Entry<String, Object>> iter = auditRecord.entrySet().iterator();

                    while (iter.hasNext()) {
                        Map.Entry<String, Object> itemEntry = iter.next();
                        if (!(itemEntry.getValue() instanceof JSONObject))
                            continue;
                        JSONObject item = (JSONObject) itemEntry.getValue();
                        Iterator<Map.Entry<String, Object>> innerIter = item.entrySet().iterator();
                        while (innerIter.hasNext()) {
                            Map.Entry<String, Object> inner = innerIter.next();
                            String key = inner.getKey();
                            if (!(inner.getValue() instanceof JSONObject))
                                continue;
                            JSONObject ele = (JSONObject) inner.getValue();
                            if(ele.containsKey("val")&&null!=ele.get("val")&&!"".equals(ele.get("val")))
                                if (ele.containsKey("type") && "字段".equals(ele.getString("type"))) {
                                    if (!src.containsKey(key) || !src.getString(key).equals(ele.getString("val"))) {
                                        uploadText.put(key, ele.getString("val"));
                                    }
                                }
                        }
                    }

                    String email = record.getString("email");
                    String password = record.getString("password");
                    RemoteConn ins = RemoteConn.createPrivateInstance(email, password);
                    boolean flag_ok = true;
                    if (ins.isAuthed()) {
                        if ("第一阶段".equals(record.getString(srcStateName))) {
                            JSONObject re = ins.uploadText(id, uploadText);
                            if (re != null && re.containsKey("code") && re.getInteger("code").equals(0)) {
                                record.put("rawRecord", re.getJSONObject("data"));
                                log.add(sdf.format(new Date()) + ":审核提交第一阶段完成");
                                appendInfo(sdf.format(new Date()) + ":审核提交第一阶段完成.id=" + id);
                                record.put(srcStateName, "第二阶段");
                            } else {
                                log.add(sdf.format(new Date()) + ":审核提交第一阶段失败");
                                appendInfo("审核提交字段上传失败.id=" + id + "." + (re == null ? "" : re.getString("msg")));
                                flag_ok = false;
                            }
                        }

                        if ("第二阶段".equals(record.getString(srcStateName))) {
                            File moduleDir = new File(ZRXUTIL.getPath() + "/" + id + "/审核");
                            if (moduleDir.exists() && moduleDir.isDirectory()) {
                                File[] files = moduleDir.listFiles();
                                if (files != null) {
                                    for (File file : files) {
                                        if (file.exists() && file.isFile() && !(file.getName().lastIndexOf(".raw") > -1)) {
                                            String key = file.getName().substring(0, file.getName().lastIndexOf("."));
                                            String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
                                            JSONObject re = ins.uploadFiles(id, key, file.getAbsolutePath(), suffix);
                                            if (re != null
                                                    && re.containsKey("code")
                                                    && re.getInteger("code").equals(0)
                                                    && re.containsKey("details")) {
                                                JSONObject details = re.getJSONObject("details");
                                                Set<String> resultDetailsKeySet = details.keySet();
                                                jobState = record.getString("id");
                                                for (String detailKey : resultDetailsKeySet) {
                                                    if ("上传失败".equals(details.getString(detailKey))) {
                                                        flag_ok = false;
                                                        jobState += detailKey + " failed;";
                                                        appendInfo("审核提交文件上传失败:" + detailKey + ".id=:" + id);
                                                    } else {
                                                        appendInfo("审核提交文件上传成功:" + detailKey + ".id=:" + id);
                                                        file.delete();
                                                    }
                                                }
                                                record.put("rawRecord", re.getJSONObject("data"));
                                                ZRXUTIL.saveState(record, true);
                                            } else
                                                flag_ok = false;
                                        }
                                    }
                                }
                            }
                            if(flag_ok){
                                log.add(sdf.format(new Date()) + ":审核提交第二阶段完成");
                                appendInfo(sdf.format(new Date()) + ":审核提交第二阶段完成.id=" + id);

                                record.put(srcStateName, "第三阶段");
                            }else{
                                log.add(sdf.format(new Date()) + ":审核提交第二阶段失败");
                            }
                        }

                        if ("第三阶段".equals(record.getString(srcStateName))) {
                            JSONObject re = ins.submit(id);
                            if (re != null && re.containsKey("code") && re.getInteger("code").equals(0)) {
                                record.put("rawRecord", re.getJSONObject("data"));
                                record.remove("editable");
                                record.remove("state");
                                record.remove(srcStateName);
                                record.remove("retryLog");
                                appendInfo(sdf.format(new Date()) + ":审核提交第三阶段完成.id=" + id);
                                appendInfo(sdf.format(new Date()) + ":审核提交成功.id=" + id);
                                log.add(sdf.format(new Date()) + ":审核提交完成");
                            } else {
                                appendInfo(sdf.format(new Date()) + ":审核提交失败.id=" + id + "." + (re == null ? "" : re.getString("msg")));
                            }
                        }
                    }
                }
            } catch (Exception e) {
                appendInfo(sdf.format(new Date())+" 审核提交异常 id=" + id + "." + e.getMessage());
            } finally {
                ZRXUTIL.saveState(record,true);
            }
        }
    }

}
